package shuangzu.top.zzurla.activities;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import shuangzu.top.zzurla.R;
import shuangzu.top.zzurla.utils.CircleImageView;

import java.util.concurrent.ExecutionException;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private TextView txt_stu_name;
    private TextView txt_stu_college;
    //private ImageView headpic;
    private CircleImageView headpic;
    private String imgpath="";
    private String stu_name="";
    private String stu_college="";
    private View headerView;
    private String labid="";
    private Handler handler;
    private FragmentManager fragmentManager;

    private bulletin_fragment bull_fragment;
    private userinfo_fragment user_fragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        handler=new Handler();
        setSupportActionBar(toolbar);
/*
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "正在刷新", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();

                //打开公告界面
                bulletin_fragment fragment=new bulletin_fragment();
                FragmentManager fragmentManager =getFragmentManager();
                FragmentTransaction transaction =fragmentManager.beginTransaction();
                transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                transaction.replace(R.id.zzuframelayout,fragment);
                transaction.commit();

            }
        });
        */

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        headerView=navigationView.inflateHeaderView(R.layout.nav_header_main);
        fragmentManager =getFragmentManager();
        FragmentTransaction transaction;
        transaction =fragmentManager.beginTransaction();
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        bull_fragment=new bulletin_fragment();
        user_fragment=new userinfo_fragment();
        transaction.add(R.id.zzuframelayout,user_fragment,"user");
        transaction.add(R.id.zzuframelayout,bull_fragment,"bull").show(bull_fragment);
        transaction.commit();
        new Thread(){
            public void run()
            {

                txt_stu_name=(TextView)headerView.findViewById(R.id.stu_name);
                txt_stu_college=(TextView)headerView.findViewById(R.id.stu_college);
                headpic=(CircleImageView) headerView.findViewById(R.id.headpic);
                SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
                String username=pref.getString("username","我走之前");

                try{
                    OkHttpClient client =new OkHttpClient();
                    Request request=new Request.Builder()
                            .url("http://server.aspi.tech:8080/zrla/student/findbyid?stu_id="+username)
                            .get()
                            .build();
                    Response response=client.newCall(request).execute();
                    String responseData=response.body().string();
                    JSONObject jsonObject =JSONObject.parseObject(responseData);
                    imgpath=jsonObject.getString("stu_img");
                    stu_name=jsonObject.getString("stu_name");
                    stu_college=jsonObject.getString("stu_college");
                    SharedPreferences.Editor editor;
                    editor=pref.edit();
                    editor.putString("stu_name",stu_name);
                    editor.putString("stu_img",imgpath);
                    editor.putString("lab_id",jsonObject.getString("lab_id"));
                    labid=jsonObject.getString("lab_id");
                    editor.putString("stu_college",stu_college);
                    editor.putString("stu_sex",jsonObject.getString("stu_sex"));
                    editor.putString("stu_birth",jsonObject.getString("stu_birth"));
                    editor.putString("stu_nation",jsonObject.getString("stu_nation"));
                    editor.putString("stu_phone",jsonObject.getString("stu_phone"));
                    editor.putString("stu_room",jsonObject.getString("stu_room"));
                    editor.putString("stu_major",jsonObject.getString("stu_major"));
                    editor.putString("stu_email",jsonObject.getString("stu_email"));
                    editor.apply();

                }catch (Exception e)
                {
                    e.printStackTrace();
                }

                try{
                    OkHttpClient client =new OkHttpClient();
                    Request request=new Request.Builder()
                            .url("http://server.aspi.tech:8080/zrla/lab/findbyid?lab_id="+labid)
                            .get()
                            .build();
                    Response response=client.newCall(request).execute();
                    String responseData=response.body().string();
                    JSONObject jsonObject =JSONObject.parseObject(responseData);
                    SharedPreferences.Editor editor;
                    editor=pref.edit();
                    editor.putString("lab_name",jsonObject.getString("lab_name"));
                    editor.putString("lab_manager_id",jsonObject.getString("lab_manager_id"));
                    stu_college=jsonObject.getString("lab_name");
                    editor.apply();

                }catch (Exception e)
                {
                    e.printStackTrace();

                }



                handler.post(changeUI_info);

            }
        }.start();

        //Glide.with(MainActivity.this)
        //        .load(imgpath)
        //        .fallback(R.drawable.ic_luncher_dabai)

        //        .into(headpic);



    }

    @Override
    protected  void onResume() {

        super.onResume();
    }

    Runnable changeUI_info=new Runnable() {
        @Override
        public void run() {
            txt_stu_name = (TextView) headerView.findViewById(R.id.stu_name);
            txt_stu_college = (TextView) headerView.findViewById(R.id.stu_college);
            headpic = (CircleImageView) headerView.findViewById(R.id.headpic);

            txt_stu_name.setText(stu_name);
            txt_stu_college.setText(stu_college);
            ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(MainActivity.this));
            DisplayImageOptions options = new DisplayImageOptions.Builder()
                    .showImageForEmptyUri(R.drawable.ic_luncher_dabai)
                    .showImageOnFail(R.drawable.ic_luncher_dabai)
                    .showImageOnLoading(R.drawable.ic_luncher_dabai)
                    .build();
            ImageLoader.getInstance().displayImage(imgpath,headpic,options);

        }
    };



    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }



    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_wp) {
            // 打开网盘界面
            Intent intent=new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("https://pan.shuangzu.top/index.php?user/login"));
            startActivity(intent);
        } else if (id == R.id.nav_qd) {
            //打开签到界面
            Intent intent =new Intent(MainActivity.this,checkio_activity.class);
            startActivity(intent);

        } else if (id == R.id.nav_gg) {
            //打开公告界面


            FragmentTransaction transaction=fragmentManager.beginTransaction();
            transaction.hide(user_fragment);
            transaction.show(bull_fragment);
            //transaction.replace(R.id.zzuframelayout,bull_fragment);
            transaction.commit();

        } else if(id==R.id.nav_about){
            Intent intent =new Intent(MainActivity.this,contects_activity.class);
            startActivity(intent);
        } else if (id==R.id.nav_exit){
            Intent intent =new Intent(MainActivity.this,login_activity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else if (id==R.id.nav_aboutme)
        {
            FragmentTransaction transaction=fragmentManager.beginTransaction();
            transaction.hide(bull_fragment);
            transaction.show(user_fragment);
            //transaction.replace(R.id.zzuframelayout,user_fragment);
            transaction.commit();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

}
